﻿using System;
using System.Collections.Generic;
using System.Windows;
using Byond.Frontend.ViewModels;
using Mvvm;
using System.Linq;

namespace Byond.Frontend.Views
{
	internal partial class CachedDocumentEditorHost
	{
		private readonly ViewFactory _viewFactory;
		private readonly List<Tuple<string, EnsembleEditorView>> _viewCache = new List<Tuple<string, EnsembleEditorView>>();

		public CachedDocumentEditorHost(ViewFactory viewFactory, IDocumentManager documentManager)
		{
			_viewFactory = viewFactory;
			documentManager.DocumentDiscarded += RemoveViewFromCache;

			InitializeComponent();
		}

		private EnsembleEditorViewModel _ensembleEditorViewModel;
		public EnsembleEditorViewModel EnsembleEditorViewModel
		{
			get { return _ensembleEditorViewModel; }
			set
			{
				_ensembleEditorViewModel = value;
				if (value == null)
					return;

				var view = _viewCache.FirstOrDefault(it => it.Item1 == value.Document.FileName);
				if (view != null)
				{
					Content = view.Item2;

					// give the editor keyboard focus so that the caret position is restored.
					view.Item2.Loaded += EnsembleEditorViewOnLoaded;
				}
				else
				{
					var newView = (EnsembleEditorView)_viewFactory.GetViewForModel(value);
					_viewCache.Add(new Tuple<string, EnsembleEditorView>(value.Document.FileName, newView));
					Content = newView;
				}
			}
		}

		private static void EnsembleEditorViewOnLoaded(object sender, RoutedEventArgs routedEventArgs)
		{
			var ensembleEditorView = (EnsembleEditorView)sender;
			var viewModel = (EnsembleEditorViewModel)ensembleEditorView.DataContext;

			if (viewModel.IsInSourceMode)
				ensembleEditorView.SourceCode.SetFocusOnCarret();
			else
				ensembleEditorView.UiCode.SetFocusOnCarret();

			ensembleEditorView.Loaded -= EnsembleEditorViewOnLoaded;
		}

		private void RemoveViewFromCache(string fileName)
		{
			var views = _viewCache.Where(it => it.Item1 == fileName).ToList();
			foreach (var view in views)
			{
				view.Item2.Loaded -= EnsembleEditorViewOnLoaded;
				_viewCache.Remove(view);
			}
		}
	}
}
